<template>
    <el-row>
        <el-col :span="12">
            <el-card>
                <div id="top5DnameAndCountDiv" style="width: 600px;height: 450px;"></div>
            </el-card>
        </el-col>
        <el-col :span="12">
            <el-card>
                <div id="top5PnameAndCountDiv" style="width: 600px;height: 450px;"></div>
            </el-card>
        </el-col>
        <!-- 添加新的折线图容器 -->
        <el-col :span="24">
            <el-card>
                <el-row>
                    <el-col :span="4">
                        <el-select v-model="selectedPartId" placeholder="选择配件" @change="updateInventoryChart">
                            <el-option
                                v-for="part in partList"
                                :key="part.partId"
                                :label="part.partName"
                                :value="part.partId"
                            ></el-option>
                        </el-select>
                    </el-col>
                </el-row>
                <div id="inventoryChart" style="width: 100%; height: 450px;"></div>
            </el-card>
        </el-col>
    </el-row>
</template>

<script setup>
import adminApi from "@/api/adminApi";
import * as echarts from "echarts";
import { onMounted, ref } from "vue";
import repairerApi from "@/api/repairerApi.js";

// 配件列表和当前选中的配件ID
const partList = ref([]);
const selectedPartId = ref(null);

// 获取配件列表
function getParts() {
    repairerApi.getAllParts()
        .then(resp => {
            console.log('配件数据响应:', resp);

            // 直接使用返回的数组
            if (Array.isArray(resp)) {
                partList.value = resp;

                // 如果有数据，默认选中第一个配件
                if (resp.length > 0) {
                    selectedPartId.value = resp[0].partId;
                    // 自动加载第一个配件的数据
                    updateInventoryChart();
                }
            } else {
                console.error('获取的配件数据格式不正确:', resp);
            }
        })
        .catch(error => {
            console.error('获取配件信息失败', error);
        });
}

// 更新库存图表
function updateInventoryChart() {
    if (!selectedPartId.value) return;

    adminApi.all(selectedPartId.value)
        .then(resp => {
            console.log('库存数据响应:', resp);

            // 假设RespBean格式为 { status: 200, message: "", data: [...] }
            if (resp && resp.data && Array.isArray(resp.data)) {
                renderInventoryChart(resp.data);
            } else {
                console.error('获取的库存数据格式不正确:', resp);
            }
        })
        .catch(error => {
            console.error('获取库存数据失败:', error);
        });
}

// 渲染库存图表（包含预测功能）
function renderInventoryChart(data) {
    if (!data || data.length === 0) {
        console.log('没有找到该配件的库存数据');
        return;
    }

    // 提取月份、入库数量、出库数量数据
    const months = data.map(item => item.month);
    const inQty = data.map(item => item.totalInQty || 0);
    const outQty = data.map(item => item.totalOutQty || 0);

    // 获取配件名称用于标题
    const partName = data[0].partName || '未知配件';

    // 使用移动平均法预测未来三个月的数据
    const forecastMonths = 3;
    const forecastInQty = forecastTimeSeries(inQty, forecastMonths);
    const forecastOutQty = forecastTimeSeries(outQty, forecastMonths);

    // // 生成未来三个月的日期标签
    // const lastMonthDate = new Date(months[months.length - 1] + '-01');
    // const futureMonths = [];
    // for (let i = 1; i <= forecastMonths; i++) {
    //     const nextMonthDate = new Date(lastMonthDate);
    //     nextMonthDate.setMonth(nextMonthDate.getMonth() + i);
    //     const year = nextMonthDate.getFullYear();
    //     const month = (nextMonthDate.getMonth() + 1).toString().padStart(2, '0');
    //     futureMonths.push(`${year}-${month}`);
    // }

    // 合并原始数据和预测数据
    const allMonths = [...months];
    const allInQty = [...inQty, ...forecastInQty];
    const allOutQty = [...outQty, ...forecastOutQty];
1
    // 标记预测数据的范围
    const predictionStartIndex = months.length;

    // 初始化echarts实例
    const myChart = echarts.init(document.getElementById('inventoryChart'));

    // 配置项
    const option = {
        title: {
            text: `${partName} 月度出入库趋势与预测`,
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            },
            formatter: function (params) {
                let result = `${params[0].name}<br/>`;
                params.forEach(item => {
                    const isPrediction = item.dataIndex >= predictionStartIndex;
                    const label = isPrediction ? `${item.seriesName} (预测): ` : `${item.seriesName}: `;
                    result += `${label}${item.value}<br/>`;
                });
                return result;
            }
        },
        legend: {
            data: ['入库数量', '出库数量', '入库预测', '出库预测'],
            top: '5%',
            left: 'center'
        },
        xAxis: {
            type: 'category',
            data: allMonths,
            axisLabel: {
                rotate: 45,
                interval: 0 // 强制显示所有标签
            }
        },
        yAxis: {
            type: 'value',
            name: '数量',
            min: 0,
            axisLabel: {
                formatter: '{value}'
            }
        },
        series: [
            {
                name: '入库数量',
                type: 'line',
                data: inQty,
                itemStyle: {
                    color: '#327ab7'
                },
                lineStyle: {
                    width: 2
                },
                symbol: 'circle',
                symbolSize: 6
            },
            {
                name: '入库预测',
                type: 'line',
                data: forecastInQty,
                itemStyle: {
                    color: '#327ab7'
                },
                lineStyle: {
                    type: 'dashed',
                    width: 2
                },
                symbol: 'circle',
                symbolSize: 6,
                label: {
                    show: true,
                    position: 'top',
                    formatter: function (params) {
                        return Math.round(params.value);
                    }
                }
            },
            {
                name: '出库数量',
                type: 'line',
                data: outQty,
                itemStyle: {
                    color: '#d9534f'
                },
                lineStyle: {
                    width: 2
                },
                symbol: 'circle',
                symbolSize: 6
            },
            {
                name: '出库预测',
                type: 'line',
                data: forecastOutQty,
                itemStyle: {
                    color: '#d9534f'
                },
                lineStyle: {
                    type: 'dashed',
                    width: 2
                },
                symbol: 'circle',
                symbolSize: 6,
                label: {
                    show: true,
                    position: 'top',
                    formatter: function (params) {
                        return Math.round(params.value);
                    }
                }
            }
        ]
    };

    // 使用刚指定的配置项和数据显示图表
    myChart.setOption(option);

    // 监听窗口大小变化，调整图表
    window.addEventListener('resize', () => {
        myChart.resize();
    });
}

// 简单移动平均法进行时间序列预测
function forecastTimeSeries(data, steps) {
    // 使用最近3个月的数据计算移动平均作为预测值
    const windowSize = Math.min(3, data.length);
    const forecast = [];

    for (let i = 0; i < steps; i++) {
        // 获取用于计算平均值的数据窗口
        const windowData = [...data.slice(-windowSize), ...forecast];
        const avg = windowData.slice(-windowSize).reduce((sum, val) => sum + val, 0) / windowSize;

        // 添加季节性调整（简单模拟，可根据实际情况调整）
        const seasonalFactor = 1 + (i % 12) * 0.05; // 轻微的季节性波动
        forecast.push(Math.round(avg * seasonalFactor));
    }

    return forecast;
}

// 定义函数显示图表
function chcra01() {
    adminApi.top5()
        .then((resp) => {
            let data = new Array();
            let count = new Array();

            for (let index = 0; index < resp.data.length; index++) {
                data.push(resp.data[index].dname);
                count.push(resp.data[index].count);
            }

            var myChart = echarts.init(document.getElementById("top5DnameAndCountDiv"));

            // 指定图表的配置项和数据
            var option = {
                title: {
                    text: "前5的部门和人数占比",
                    textStyle: {
                        color: "#000000",
                        fontWeight: "lighter",
                    },
                },
                tooltip: {
                    trigger: "item",
                },
                legend: {
                    top: "5%",
                    left: "center",
                },
                series: [
                    {
                        name: "部门人数占比",
                        type: "pie",
                        radius: ["40%", "70%"],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: "#fff",
                            borderWidth: 2,
                        },
                        label: {
                            show: false,
                            position: "center",
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: "40",
                                fontWeight: "bold",
                            },
                        },
                        labelLine: {
                            show: false,
                        },
                        data: data.map((item, index) => ({
                            value: count[index],
                            name: item,
                        })),
                    },
                ],
            };

            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
        });
}

// 保留原有的图表初始化函数
function chart02() {
    adminApi.rtop5().then((resp) => {
        let data = [];
        let count = [];

        for (let index = 0; index < resp.data.length; index++) {
            data.push(resp.data[index].rname);
            count.push(resp.data[index].count);
        }

        const myChart = echarts.init(
            document.getElementById("top5PnameAndCountDiv")
        );

        const option = {
            title: {
                text: "参与维修事件总数前五的维修人员",
                textStyle: {
                    color: "#000000",
                    fontWeight: "lighter",
                },
            },
            legend: {
                data: ["维修项目总数"],
                right: "10%",
                itemWidth: 10,
                itemHeight: 10,
                textStyle: {
                    color: "#000000",
                },
            },
            xAxis: {
                data: data,
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "#000000",
                        width: 1,
                    },
                },
                splitLine: {
                    show: false,
                },
            },
            yAxis: {
                axis线: {
                    show: true,
                    lineStyle: {
                        color: "#000000",
                        width: 1,
                    },
                },
                splitLine: {
                    show: false,
                },
            },
            series: [
                {
                    name: "维修项目总数",
                    type: "bar",
                    data: count,
                    barWidth: 30,
                    itemStyle: {
                        normal: {
                            color: function (params) {
                                let colorList = [
                                    "#4B0082",
                                    "#800080",
                                    "#8B0000",
                                    "#FF0000",
                                    "#FF6347",
                                ];
                                return colorList[params.dataIndex];
                            },
                        },
                    },
                },
            ],
        };

        myChart.setOption(option);
    });
}

// 组件挂载时初始化
onMounted(() => {
    chcra01();
    chart02();
    getParts(); // 获取配件列表
});
</script>

<style scoped></style>